package hay.component;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;


public class HayMe2day{

	private InputStream getInputStream(String para_url){
		while(true){
			try{
				URL url = new URL(para_url);
				URLConnection con= url.openConnection();
				InputStream is = con.getInputStream();
				return is;
			} catch (Exception e) {
				Log.d("mytag", e.getMessage());
				return null;
			}
		}
	}


	public ArrayList<String> getPosts(String screen_name){
		ArrayList<String> stringList = new ArrayList<String>();

		try {

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
			factory.setNamespaceAware(true); 
			XmlPullParser xpp = factory.newPullParser(); 
			InputStream stream = getInputStream("http://me2day.net/api/get_posts/"+screen_name+".xml");
			if(stream!=null){
				xpp.setInput(stream, "UTF-8"); 
				int eventType = xpp.getEventType(); 
				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch(eventType){
					case XmlPullParser.START_DOCUMENT:
						//Log.d("mytag","Start document");
						break;
					case XmlPullParser.END_DOCUMENT:
						//Log.d("mytag","End document");
						break;
					case XmlPullParser.START_TAG:
						//Log.d("mytag","Start tag "+xpp.getName());
						if(xpp.getName().equals("body")){
							eventType = xpp.next();
							String text = xpp.getText();
							stringList.add(text);
						}
						break;
					case XmlPullParser.END_TAG:
						//Log.d("mytag","End tag "+xpp.getName());
						break;
					case XmlPullParser.TEXT:
						//Log.d("mytag","Text "+xpp.getText());
						break;	
					}
					eventType = xpp.next();
				}

				return stringList;
			}
			else{
				return null;
			}
		}
		catch(Exception e){
			Log.d("mytag", e.getMessage());
			return null;
		}
	}
}